package org.fastsyncer.connector.sql;

import org.fastsyncer.common.entity.BaseInfo;
import org.fastsyncer.common.entity.DatabaseConfig;
import org.fastsyncer.connector.common.DatabaseConstant;
import org.fastsyncer.connector.framework.AbstractDatabaseConnector;
import org.fastsyncer.connector.util.DatabaseUtil;
import org.springframework.jdbc.core.JdbcTemplate;

public final class SqlOracleConnector extends AbstractDatabaseConnector {

    private static volatile SqlOracleConnector instance = null;

    private SqlOracleConnector() {
    }

    public static SqlOracleConnector getInstance() {
        if (null == instance) {
            synchronized (SqlOracleConnector.class) {
                if (null == instance) {
                    instance = new SqlOracleConnector();
                }
            }
        }
        return instance;
    }
    
    @Override
    public BaseInfo getBaseInfoConnector(DatabaseConfig config, String queryFilter) {
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate(config);
        // SELECT * FROM USER WHERE ID = '123'
        String sql = config.getSql().toUpperCase();
        // 查询元信息
        StringBuilder metaSQL = new StringBuilder().append(sql);
        // SELECT * FROM USER WHERE ROWNUM = 0
        // SELECT * FROM USER WHERE ID = '123' AND ROWNUM = 0
        metaSQL.append(sql.contains(" WHERE ") ? " AND" : " WHERE");
        metaSQL.append(DatabaseConstant.ORACLE_PAGE_SQL_NULL);
        
        // 查询连接器基本信息
        BaseInfo connector = DatabaseUtil.getDataSourceConnector(jdbcTemplate, metaSQL.toString(), sql);
        // 释放连接
        this.close(jdbcTemplate);
        return connector;
    }

    @Override
    public StringBuilder getPageSQL(DatabaseConfig config, StringBuilder sql) {
        // Oracle 分页查询
        sql.insert(0, DatabaseConstant.ORACLE_PAGE_SQL_START);
        sql.append(DatabaseConstant.ORACLE_PAGE_SQL_END);
        return sql;
    }

}
